import type {
  ListOption,
  Namespace,
  NamespaceList
} from "../../../api/k8s/types";

import { useK8SApi } from "../../../api/k8s/k8s";
import { SourceMan } from "../providers/sourceCtl";
import type { Ref } from "vue";
import type { PromiseRes } from "@/api/response";
const { namespaceRepo } = useK8SApi();

class NamespaceProvider extends SourceMan<Namespace> {
  get nsList(): Ref<Namespace[]> {
    if (
      !this.srcList ||
      !this.srcList.value ||
      this.srcList.value.length === 0
    ) {
      this.getNamespaces();
    }
    return this.srcList;
  }

  // 获取节点列表
  getNamespaces = async (req?: ListOption): Promise<NamespaceList> => {
    const res = await namespaceRepo.getNamespaceList({
      ...(req || this.searchQuery),
      continue: this.continue,
      limit: this.pager.limit.value
    });
    if (res) {
      // this.continue = res.continue;
      this.srcList.value = res.items;
      this.pager.total.value = res.items.length;
    }
    return res;
  };

  // 获取节点详情
  getNamespaceDetails = async (name: string): PromiseRes<Namespace> => {
    const res = await namespaceRepo.getNamespaceDetail({ name });
    if (res.ok) {
      this.srcDetail.value = res.data;
      this.srcYamlContent.value = this.objectToYaml(res.data);
      this.yamlDialog.value = true;
    }
    return res;
  };

  // 更新节点
  updateNamespace = async (node?: Namespace) => {
    const res = await namespaceRepo.updateNamespace(node);
    if (res.ok) {
      this.refreshNamespaceList();
    }
  };

  // delete
  deleteNamespace = async (name: string) => {
    const res = await namespaceRepo.deleteNamespace({ name });
    if (res.ok) {
      this.refreshNamespaceList();
    }
  };

  refreshNamespaceList = async () => {
    this.continue = undefined;
    await this.getNamespaces({});
  };
}

export default new NamespaceProvider();
